﻿/*
* Do Not Remove
* Author: Douglas Branca http://www.linkedin.com/in/douglasbranca
* CodePlex: https://mvcscriptcompression.codeplex.com 
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using DB.MVC.Extensions.Compression.Resource;
using DB.MVC.Extensions.Compression.Cache;
using DB.MVC.Extensions.Compression.Configuration;

namespace DB.MVC.Extensions.Compression.Routing
{
    /// <summary>
    /// MVC CompositeResource HttpHandler, returns the requested resource.
    /// Can only be used with the CompositeResourceRouteHandler, can not be used standalone
    /// </summary>
    public class CompositeResourceHandler : IHttpHandler
    {
        private string _name;
        private ResourceType _type;

        /// <summary>
        /// Constructor takes composites resource key and type to return from route data
        /// </summary>
        /// <param name="name">Composite Resource Name</param>
        /// <param name="type">Composite resource type, css or js</param>
        public CompositeResourceHandler(string name, string type)
        {
            this._name = name;
            this._type = (ResourceType)Enum.Parse(typeof(ResourceType), type, true);
        }

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Returns the cached resource
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {

                context.Response.ContentType = (this._type == ResourceType.CSS) ? "text/css" : "text/javascript";

                context.Response.Clear();
                context.Response.Cache.SetCacheability(HttpCacheability.Private);
                if (CompositeResourceSettings.SetClientCacheExpire)
                {
                    context.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(CompositeResourceSection.Instance.ClientCacheDays));
                }
                else
                {
                    //don't expire cache
                    context.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(1));
                }

                string body = ResourceCache.GetCachedResource(this._name, context);

                context.Response.Write(body);
                
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.Write(ex.Message);
            }
        }

        #endregion
    }
}
